package handler

import (
	"context"
	"easy-note/models"
	user "easy-note/user/kitex_gen/user"
	"easy-note/user/repo"
)

// UserImpl implements the last service interface defined in the IDL.
type UserImpl struct {
	Repo repo.UserRepo
}

// CheckUser implements the UserImpl interface.
func (s *UserImpl) CheckUser(ctx context.Context, req *user.ReqCheckUser) (resp *user.ResCheckUser, err error) {
	isExist, err := s.Repo.CheckUser(req.GetUsername(), req.GetPassword())
	if err != nil {
		return &user.ResCheckUser{IsExist: false}, err
	}
	return &user.ResCheckUser{IsExist: isExist}, nil
}

// InsertUser implements the UserImpl interface.
func (s *UserImpl) InsertUser(ctx context.Context, req *user.ReqInsertUser) (resp *user.ResInsertUser, err error) {
	isSuccess, err := s.Repo.InsertUser(&models.User{
		Username: req.GetUsername(),
		Password: req.GetPassword(),
		Gender:   int(req.GetGender()),
		Avatar:   req.GetAvatar(),
	})
	if err != nil {
		return &user.ResInsertUser{IsExist: false}, err
	}
	return &user.ResInsertUser{IsExist: isSuccess}, nil
}

// GetUserByUsername implements the UserImpl interface.
func (s *UserImpl) GetUserByUsername(ctx context.Context, req *user.ReqGetUserByUsername) (resp *user.ResGetUserByUsername, err error) {
	userRepo, err := s.Repo.GetUserByUsername(req.GetUsername())
	if err != nil {
		return nil, err
	}
	return &user.ResGetUserByUsername{
		Username:  userRepo.Username,
		CreatedAt: userRepo.CreatedAt.String(),
		Avatar:    userRepo.Avatar,
		Gender:    int32(userRepo.Gender),
		UpdatedAt: userRepo.UpdatedAt.String(),
		Id:        int32(userRepo.Id),
	}, nil
}
